// HttpServer.cpp
#include "HttpServer.hpp"
#include "muduo/Log.hpp"
#include <sstream>
#include <algorithm>

extern Log lg;

HttpServer::HttpServer(EventLoop* loop, int port)
    : _loop(loop), _port(port), _acceptor(loop, port) {
    _acceptor.SetAcceptCallback(std::bind(&HttpServer::onConnection, this, std::placeholders::_1));
    _acceptor.Listen();
    lg.info("HTTP Server initialized on port %d", port);
}

void HttpServer::setRequestCallback(const HttpRequestCallback& cb) {
    _request_callback = cb;
}

void HttpServer::start() {
    lg.info("HTTP Server started");
}

void HttpServer::onConnection(int sockfd) {
    // 创建 HTTP 连接处理器
    auto conn = std::make_shared<Connection>(_loop, 0, sockfd);
    
    conn->SetMessageCallback([this](const PtrConnection& connection, Buffer* buffer) {
        try {
            std::string request = buffer->ReadAsStringAndPop(buffer->ReadAbleSize());
            
            std::string method, path, body;
            auto headers = parseHeaders(parseHttpRequest(request, method, path, body));
            
            std::string response;
            if (_request_callback) {
                _request_callback(method, path, headers, body, response);
            } else {
                response = "HTTP/1.1 404 Not Found\r\nContent-Length: 0\r\n\r\n";
            }
            
            connection->Send(response.c_str(), response.length());
        } catch (const std::exception& e) {
            lg.error("HTTP request processing error: %s", e.what());
        }
    });
    
    conn->Established();
}

std::map<std::string, std::string> HttpServer::parseHeaders(const std::string& request) {
    std::map<std::string, std::string> headers;
    std::istringstream iss(request);
    std::string line;
    
    // 跳过第一行（请求行）
    std::getline(iss, line);
    
    while (std::getline(iss, line) && line != "\r") {
        size_t pos = line.find(':');
        if (pos != std::string::npos) {
            std::string key = line.substr(0, pos);
            std::string value = line.substr(pos + 2); // 跳过冒号和空格
            
            // 去除回车符
            if (!value.empty() && value.back() == '\r') {
                value.pop_back();
            }
            
            // 转换键为小写
            std::transform(key.begin(), key.end(), key.begin(), ::tolower);
            headers[key] = value;
        }
    }
    
    return headers;
}

std::string HttpServer::parseHttpRequest(const std::string& request, 
                                        std::string& method, 
                                        std::string& path, 
                                        std::string& body) {
    std::istringstream iss(request);
    std::string line;
    
    // 解析请求行
    if (std::getline(iss, line)) {
        std::istringstream lineStream(line);
        lineStream >> method >> path;
    }
    
    // 查找请求体分隔符
    size_t bodyPos = request.find("\r\n\r\n");
    if (bodyPos != std::string::npos) {
        body = request.substr(bodyPos + 4);
    }
    
    // 返回头部部分
    return request.substr(0, bodyPos);
}